import 'package:flutter/material.dart';
import '../models/fishing_report.dart';
import '../services/fishing_report_service.dart';

class FishingReportProvider with ChangeNotifier {
  List<FishingReport> _reports = [];
  FishingStats? _stats;
  bool _isLoading = false;
  bool _isLoadingMore = false;
  String? _error;
  int _currentPage = 1;
  bool _hasMore = true;

  // 过滤条件
  String? _selectedLocation;
  String? _selectedFishType;
  String? _selectedDifficulty;

  // Getters
  List<FishingReport> get reports => _reports;
  FishingStats? get stats => _stats;
  bool get isLoading => _isLoading;
  bool get isLoadingMore => _isLoadingMore;
  String? get error => _error;
  bool get hasMore => _hasMore;
  String? get selectedLocation => _selectedLocation;
  String? get selectedFishType => _selectedFishType;
  String? get selectedDifficulty => _selectedDifficulty;

  // 加载钓况报告列表
  Future<void> loadReports({bool refresh = false}) async {
    if (refresh) {
      _currentPage = 1;
      _hasMore = true;
      _reports.clear();
    }

    if (_isLoading || _isLoadingMore) return;

    if (refresh || _currentPage == 1) {
      _isLoading = true;
    } else {
      _isLoadingMore = true;
    }
    _error = null;
    notifyListeners();

    try {
      final newReports = await FishingReportService.getFishingReports(
        page: _currentPage,
        pageSize: 10,
        location: _selectedLocation,
        fishType: _selectedFishType,
        difficulty: _selectedDifficulty,
      );

      if (newReports.isEmpty) {
        _hasMore = false;
      } else {
        if (refresh || _currentPage == 1) {
          _reports = newReports;
        } else {
          _reports.addAll(newReports);
        }
        _currentPage++;
      }
    } catch (e) {
      _error = '加载失败：$e';
    } finally {
      _isLoading = false;
      _isLoadingMore = false;
      notifyListeners();
    }
  }

  // 加载统计数据
  Future<void> loadStats() async {
    try {
      _stats = await FishingReportService.getFishingStats();
      notifyListeners();
    } catch (e) {
      debugPrint('加载统计数据失败：$e');
    }
  }

  // 设置位置过滤
  void setLocationFilter(String? location) {
    if (_selectedLocation != location) {
      _selectedLocation = location;
      loadReports(refresh: true);
    }
  }

  // 设置鱼类过滤
  void setFishTypeFilter(String? fishType) {
    if (_selectedFishType != fishType) {
      _selectedFishType = fishType;
      loadReports(refresh: true);
    }
  }

  // 设置难度过滤
  void setDifficultyFilter(String? difficulty) {
    if (_selectedDifficulty != difficulty) {
      _selectedDifficulty = difficulty;
      loadReports(refresh: true);
    }
  }

  // 清除所有过滤条件
  void clearFilters() {
    bool hasFilters = _selectedLocation != null || 
                     _selectedFishType != null || 
                     _selectedDifficulty != null;
    
    if (hasFilters) {
      _selectedLocation = null;
      _selectedFishType = null;
      _selectedDifficulty = null;
      loadReports(refresh: true);
    }
  }

  // 点赞/取消点赞
  Future<void> toggleLike(String reportId) async {
    try {
      final success = await FishingReportService.toggleLike(reportId);
      if (success) {
        // 更新本地数据
        final index = _reports.indexWhere((report) => report.id == reportId);
        if (index != -1) {
          final report = _reports[index];
          final newLikeCount = report.isLiked ? report.likeCount - 1 : report.likeCount + 1;
          
          _reports[index] = FishingReport(
            id: report.id,
            title: report.title,
            location: report.location,
            fishingSpotName: report.fishingSpotName,
            reportDate: report.reportDate,
            reporterName: report.reporterName,
            reporterAvatar: report.reporterAvatar,
            fishTypes: report.fishTypes,
            fishCount: report.fishCount,
            totalWeight: report.totalWeight,
            weatherCondition: report.weatherCondition,
            temperature: report.temperature,
            windDirection: report.windDirection,
            windSpeed: report.windSpeed,
            waterCondition: report.waterCondition,
            waterTemperature: report.waterTemperature,
            baitUsed: report.baitUsed,
            fishingTechnique: report.fishingTechnique,
            timeRange: report.timeRange,
            images: report.images,
            content: report.content,
            likeCount: newLikeCount,
            commentCount: report.commentCount,
            isLiked: !report.isLiked,
            rating: report.rating,
            difficulty: report.difficulty,
            tips: report.tips,
          );
          notifyListeners();
        }
      }
    } catch (e) {
      debugPrint('点赞操作失败：$e');
    }
  }

  // 获取热门鱼类列表
  List<String> get popularFishTypes {
    if (_stats?.fishTypeStats == null) return [];
    
    var entries = _stats!.fishTypeStats.entries.toList();
    entries.sort((a, b) => b.value.compareTo(a.value));
    return entries.take(5).map((e) => e.key).toList();
  }

  // 获取热门钓点列表
  List<String> get popularSpots {
    if (_stats?.spotStats == null) return [];
    
    var entries = _stats!.spotStats.entries.toList();
    entries.sort((a, b) => b.value.compareTo(a.value));
    return entries.take(5).map((e) => e.key).toList();
  }
}